<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace kitego\extend\storage;

use app\dao\setting\AttachmentStorageDao;
use kitego\enums\StorageEnum;
use kitego\extend\storage\impl\AliyunImpl;
use kitego\extend\storage\impl\LocalImpl;
use kitego\extend\storage\impl\QCloudImpl;
use kitego\extend\storage\impl\QiniuImpl;

class StorageProvider
{
    protected $strategy;

    public function __construct($storageId = 0)
    {
        // 获取存储引擎
        $config = $this->getConfig($storageId);

        // 匹配存储引擎
        if ($config['type'] == StorageEnum::ALIYUN) {
            $this->strategy = new AliyunImpl($config);
        } else if ($config['type'] == StorageEnum::QINIU) {
            $this->strategy = new QiniuImpl($config);
        } else if ($config['type'] == StorageEnum::QCLOUD) {
            $this->strategy = new QCloudImpl($config);
        } else if ($config['type'] == StorageEnum::LOCAL) {
            $this->strategy = new LocalImpl($config);
        }
    }

    public function getStrategy()
    {
        return $this->strategy;
    }

    /**
     * 静态工厂方法，快速获取策略实例
     */
    public static function for($type = 0)
    {
        $provider = new self($type);

        return $provider->getStrategy();
    }

    public function getConfig($storageId)
    {
        $where = empty($storageId) ? [['active', '=', 1]] : $storageId;
        $storageQuery = app()->make(AttachmentStorageDao::class)->find($where);

        return $storageQuery ?? ['type' => StorageEnum::LOCAL];
    }
}